package com.example.es.util;

import com.example.es.entity.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 增删改文档
 * @author: ruoan
 * @date: 2020/10/11 11:57
 */
public class EsRestHighLevelClientTest3 {

    private RestHighLevelClient client= EsRestHighLevelClient.getClient();
    private final String index = "person";
    private final String type = "_doc";  //es默认type=_doc


    /**
     * 创建文档
     */
    @Test
    public void createDoc() throws IOException {
        Person p = new Person(1,"张三",18,new Date());
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(p);
        System.out.println(jsonStr);
        IndexRequest indexRequest = new IndexRequest(index, type, p.getId()+"");
        indexRequest.source(jsonStr, XContentType.JSON);
        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.getResult());
    }




    /**
     * 修改文档
     */
    @Test
    public void updateDoc() throws IOException {


        Map<String, Object> map = new HashMap<>();
        map.put("name", "章三");


        UpdateRequest updateRequest = new UpdateRequest(index,type,"1");
        updateRequest.doc(map);

        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.getResult().toString());
    }




    /**
     * 删除文档
     */
    @Test
    public void deleteDoc() throws IOException {


        DeleteRequest deleteRequest = new DeleteRequest(index, type, "1");
        DeleteResponse delete = client.delete(deleteRequest);
        System.out.println(delete.getResult().toString());
    }





}